package com.mvc.common;

import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlBuilder {

	public XmlBuilder(){
		
	}
	
	public HashMap<String,String> parseElement(String xmlPath) throws Exception{
		HashMap<String,String> map = new HashMap<String,String>();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(this.getClass().getResourceAsStream(xmlPath)); 
        Element root = doc.getDocumentElement();
        NodeList nodeList = root.getChildNodes();
        for(int i=0;i<nodeList.getLength();i++){
        	Node node = nodeList.item(i);
        	//action form
        	if("form-beans".equals(node.getNodeName())){
        		NodeList formBeanList = node.getChildNodes();
        		for(int j=0;j<formBeanList.getLength();j++){
        			Node formBean = formBeanList.item(j);
        			if("form-bean".equals(formBean.getNodeName())){
        				String key = formBean.getAttributes().getNamedItem("name").getNodeValue();
        				String value = formBean.getTextContent();
        				map.put(key, value);
        			}
        		}
        	}
        	if("action-mappings".equals(node.getNodeName())){
        		NodeList actionMappingList = node.getChildNodes();
        		for(int j=0;j<actionMappingList.getLength();j++){
        			Node actionMapping = actionMappingList.item(j);
        			if("action-mapping".equals(actionMapping.getNodeName())){
        				String key = actionMapping.getAttributes().getNamedItem("name").getNodeValue();
        				String value = actionMapping.getTextContent();
        				map.put(key, value);
        			}
        		}
        	}
        	if("action-forwards".equals(node.getNodeName())){
        		NodeList actionForwardList = node.getChildNodes();
        		for(int j=0;j<actionForwardList.getLength();j++){
        			Node actionForward = actionForwardList.item(j);
        			if("action-forward".equals(actionForward.getNodeName())){
        				String key = actionForward.getAttributes().getNamedItem("name").getNodeValue();
        				String value = actionForward.getTextContent();
        				map.put(key, value);
        			}
        		}
        	}
        }
        System.out.println("MVC XML:" + map);
        return map;
	}
	
	public static void main(String[] args) {
		XmlBuilder x = new XmlBuilder();
		try {
			x.parseElement("/common_servlet.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
